import React, { Component } from 'react'
import './myMessage.less'
import Head from '../../../components/head/hrader'
import axios from 'axios'
import cookies from 'js-cookie'
import imgsrc from '../../../img/morentouxiang.png'
import { connect } from 'react-redux';
import fun from '../../../store/action/index'
class MyMessage extends Component {
    constructor() {
        super()
        this.state = {
            headtitle: { title: '个人信息', path: '/my' },
            myMessagedata: [//信息
                { title: '头像', age: '' },
                { title: '昵称', age: '' },
                { title: '性别', age: '' },
                { title: '生日', age: '' },
                { title: '手机号码', age: '' },
                { title: '邮箱', age: '' },
            ],
            myMessagesite: [//地址
                { title: '个性签名', age: '' },
                { title: '收货地址', age: '' },
            ],
            MySetMessage: {},//修改传递
            pathSrc: imgsrc,//'',
            videoSrc: '',
            videoaccept: "",//拍摄的格式 "image/*"
            videocapture: "",//拍摄     "camera"
            videobrowserRedirect: null,//判断设备pc   1 手机   0 pc
            videoNow: false,//摄像头弹层
            user_data: {},//数据
            // context: canvas.getContext('2d'),
            MediaStreamTrack: null,//媒体流跟踪
        }
    }
    render() {
        let { headtitle, myMessagedata, myMessagesite, videoNow, user_data } = this.state
        console.log(this.props);
        return (
            <div className="myMessage_box">
                <div className="myMessage_header">
                    <Head title={headtitle} />
                </div>
                {/* 个人信息 */}
                <div className="myMessage_body">
                    {myMessagedata.map((item, index) => {
                        return <div className="myMessage_content"
                            onClick={() => { this.MySetMessage(index) }}
                            key={index}>
                            <div>{item.title}</div>
                            <div>
                                <p className={index === 0 ? 'myMessage_img' : null}>{index === 0 ?
                                    <img ref={(imageDom) => { this.imageDom = imageDom }} className="myMessage_image"
                                        src={this.state.pathSrc}
                                        onClick={(e) => { this.onImage(e) }}></img> : null}
                                    {index === 1 ? user_data.user_name : null}
                                    {index === 2 && user_data.user_sex ? `${user_data.user_sex === '0' ? '女' : '男'}` : null}
                                    {index === 3 ? user_data.user_birthday : null}
                                    {index === 4 ? user_data.user_phone : null}
                                    {index === 5 ? user_data.user_email : null}
                                </p>
                                <p className="iconfont icon-fanhui1"></p>
                            </div>
                        </div>
                    })}
                </div>
                {/* 地址 */}
                {/* <div className="myMessage_body">
                    {myMessagesite.map((item, index) => {
                        return <div className="myMessage_content" key={index}>
                            <div>{item.title}</div>
                            <div>
                                <p>img</p>
                                <p className="iconfont icon-fanhui1"></p>
                            </div>
                        </div>
                    })}
                </div> */}
                <input type="file" accept={this.state.videoaccept} capture={this.state.videocapture}
                    ref={(getImgDom) => { this.getImgDom = getImgDom }}
                    onChange={(e) => { this.previewHandle(e.target) }} id="myMessage_photo" />
                {videoNow ? <div className="myMessage_videoNow">
                    <video src={this.state.videoSrc} ref={(videoDom) => { this.videoDom = videoDom }} id="myMessage_video"></video>
                    <div className="myMessage_videoBtn" onClick={() => { this.download('png') }}></div>
                </div> : null}
                <canvas src="" ref={(canvasDom) => { this.canvasDom = canvasDom }} id="myMessage_canvas"></canvas>
                {/* <input type="file" accept="image/*" capture="camera" /> */}
            </div>
        )
    }
    // 修改--设置按钮
    MySetMessage = (index) => {
        if (index !== 0) {
            // 跳转页面设置信息
            this.props.history.push({
                pathname: '/MySetMessage',
                state: this.state.myMessagedata[index],
                index,
                user_data: this.state.user_data,
            })
        } else if (index === 0) {
            // 修改限制拍照的格式与内容
            this.setState({ videoaccept: "", videocapture: "" }, () => {
                // 触发打开本地文件
                this.getImgDom.click()
            })
        }
    }
    AXIOS(user_id, index, newMess) {
        axios({
            method: 'post',
            url: '/api/front_end/changeUserMess',
            data: {
                user_id,    //  user_id         用户id
                index,      // index           下标
                newMess,    // newMess         新的信息
            }
        }).then(res => {
            console.log(res.data);
            if (res.data.code === '01') {
                this.props.setNav(res.data.data)
            }
        })
    }
    // 本地图片打开
    // 
    previewHandle = (fileDOM) => {
        let _this = this
        // console.log(this.getImgDom.files);
        // console.log(fileDOM.files);
        let file = fileDOM.files[0], // 获取文件
            imageType = /^image\//,
            reader = '';
        // 文件是否为图片
        if (file) {
            if (!imageType.test(file.type)) {
                alert("请选择图片！");
                return;
            }
            // 判断是否支持FileReader    
            if (window.FileReader) {
                reader = new FileReader();
            }
            // IE9及以下不支持FileReader
            else {
                alert("您的浏览器不支持图片预览功能，如需该功能请升级您的浏览器！");
                return;
            }
            // 读取完成    
            reader.onload = function (event) {
                // 获取图片DOM
                // var img = document.getElementById("preview-img");
                // let img = this.imageDom
                // 图片路径设置为读取的图片    
                // console.log(event.target.result);//base64
                // console.log(_this.state.user_data);
                // console.log(_this.state.user_data.user_id, 0,);
                _this.AXIOS(_this.state.user_data.user_id, 0, event.target.result)
                // img.src = event.target.result;
                _this.setState({ pathSrc: event.target.result })
            };
            reader.readAsDataURL(file);
        }
    }
    // 开启摄像头
    onImage = (e) => {
        let _this = this
        let { MediaStreamTrack } = this.state
        e.stopPropagation()//取消默认事件
        // 判断设备是手机还是pc
        if (this.state.videobrowserRedirect === 1) {
            this.setState({
                videoaccept: "image/*",
                videocapture: "camera",
            }, () => {
                this.getImgDom.click()
            })
        } else {
            // pc端
            _this.setState({ videoNow: true })
            //  canvas = document.getElementById('canvas'),
            let context = this.canvasDom.getContext('2d')
            //     video = document.getElementById("video"),
            //     snap = document.getElementById("snap"),
            //     close = document.getElementById("close"),
            //     start = document.getElementById("start"),
            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                navigator.mediaDevices.getUserMedia({
                    video: true,
                    // audio: true
                }).then(function (stream) {
                    // console.log(stream);
                    _this.setState({ MediaStreamTrack: typeof stream.stop === 'function' ? stream : stream.getTracks()[0] })
                    // try {
                    // video.src = window.URL.createObjectURL(stream);
                    _this.setState({ videoSrc: window.URL.createObjectURL(stream) })
                    // } catch (e) {
                    // video.srcObject = stream;
                    // }
                    // video.play();
                    _this.videoDom.play();
                }).catch(function (err) {
                    console.log(err);
                });
            } else if (navigator.getMedia) {
                navigator.getMedia({
                    video: true
                }).then(function (stream) {
                    console.log(stream);
                    _this.setState({ MediaStreamTrack: stream.getTracks()[0] })
                    // video.src = (window.webkitURL).createObjectURL(stream);
                    _this.setState({ videoSrc: (window.webkitURL).createObjectURL(stream) })
                    // video.play();
                    _this.videoDom.play();
                }).catch(function (err) {
                    // console.log(err);
                });
            }
        }
    }
    // 判断设备是手机还是pc
    browserRedirect = () => {
        var sUserAgent = navigator.userAgent.toLowerCase();
        var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
        var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
        var bIsMidp = sUserAgent.match(/midp/i) == "midp";
        var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
        var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
        var bIsAndroid = sUserAgent.match(/android/i) == "android";
        var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
        var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
        if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
            // 手机端 
            this.setState({ videobrowserRedirect: 1, })
            console.log('手机');
        } else {
            //电脑端 
            console.log('电脑');
            this.setState({ videobrowserRedirect: 0, })
        }
    }
    //  保存图片/ 下载   
    download = (type) => {
        let { MediaStreamTrack } = this.state
        //先保存至canvas
        this.canvasDom.getContext('2d').drawImage(this.videoDom, 0, 0, 300, 150)
        // 拍照弹层false
        this.setState({ videoNow: false })

        //设置保存图片的类型   image/jpeg
        // var imgdata = this.canvasDom.toDataURL(type);
        // this.canvasDom.getContext('2d').drawImage(Img, 0, 0, width, height)
        var imgdata = this.canvasDom.toDataURL('image/jpeg');
        console.log(imgdata);//base64
        this.AXIOS(this.state.user_data.user_id, 0, imgdata)
        this.setState({ pathSrc: imgdata })
        MediaStreamTrack && MediaStreamTrack.stop();
    }
    UNSAFE_componentWillMount() {
        this.browserRedirect()//判断 pc-- 手机

        if (this.props.message) {
            let { message } = this.props
            // console.log(message);

            this.setState({
                user_data: message,//数据
                pathSrc: message.user_portrait,//头像
            })
        } else if (cookies.get('usertoken')) {
            axios({
                method: 'post',
                url: '/api/front_end/userMess',
                data: {
                    user_account: cookies.get('usertoken'),
                }
            }).then((res) => {
                let datas = res.data
                this.props.setNav(res.data.data)
                if (datas.code === '01') {
                    this.setState({
                        user_data: datas.data,//数据
                        pathSrc: datas.data.user_portrait,//头像
                    })
                }
            })
        }
    }
}
export default connect(state => state.Login, fun.loginAction)(MyMessage)
